package com.cbg.bus.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.util.RandomUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <pre></pre>
 * <small> 2018-12-19 | chenbing </small>
 */
public class OrderUtils {
    /**
     * 生成订单号
     */
    public static String out_trade_no(){
        StringBuffer sb = new StringBuffer();
        sb.append(IdUtil.simpleUUID());
        sb.append(String.valueOf(System.currentTimeMillis()));
        for(int i = 0; i < 50; i++){
            if(sb.length() == 32){
                break;
            } else if(sb.length() > 32){
                sb.delete(32, sb.length());
                break;
            } else {
                Random random = new Random();
                int ic= random.nextInt(11);
                sb.append(ic);
            }
        }
        return sb.toString();
    }

    /**
     * 获取小程序手机ip
     */
    public static String ip(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StrUtil.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StrUtil.isNotBlank(ip)&& !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    /**
     * map参数去空参数
     */
    public static Map<String, String> paraFilter(Map<String, Object> sArray) {
        Map<String, String> result = new HashMap<>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = (String)sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 时间戳生成秒
     */
    public static String timeStamp(){
        return System.currentTimeMillis()/1000+"";
    }
}
